package com.yushu.base.service.impl;

import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.toolkit.IdWorker;
import com.yushu.authority.pojo.bo.PmOrg;
import com.yushu.authority.pojo.bo.PmUser;
import com.yushu.authority.pojo.vo.PmUserVO;
import com.yushu.base.mapper.DicMapper;
import com.yushu.base.pojo.bo.Dic;
import com.yushu.base.pojo.bo.DicSet;
import com.yushu.base.pojo.vo.DicVO;
import com.yushu.base.service.DicService;
import com.yushu.base.service.DicSetService;
import com.yushu.common.execption.CgException;
import com.yushu.common.service.impl.YSBaseServiceImpl;
import com.yushu.common.shiro.ShiroUtil;
import com.yushu.common.util.bean.Father2Son;
import com.yushu.common.util.date.DateUtils;
import com.yushu.common.util.pager.Pages;
import com.yushu.common.util.string.CamelCaseUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 
 * @author test
 * @CreateDate 2020-12-03 15:47:25
 */
@Service("dicService")
public class DicServiceImpl extends YSBaseServiceImpl<DicMapper, Dic> implements DicService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private DicService dicService;
    @Autowired
    private DicSetService dicSetService;

    public Pages<DicVO> page(Pages<DicVO> page) {
        PmUser sessionUser = ShiroUtil.getSessionUser();
        EntityWrapper wrapper = new EntityWrapper<DicVO>();
        DicVO dic = page.getData();

        if (null != dic) {
            if (StringUtils.isNotEmpty(dic.getUserId())) {
                wrapper.like("t.user_id", dic.getUserId(), SqlLike.DEFAULT);
            }
            if (StringUtils.isNotEmpty(dic.getId())) {
                wrapper.like("t.id", dic.getId(), SqlLike.DEFAULT);
            }
            if (StringUtils.isNotEmpty(dic.getOrgId())) {
                wrapper.like("t.org_id", dic.getOrgId(), SqlLike.DEFAULT);
            }
            if (null != dic.getUpdateTimeBefore() && null != dic.getUpdateTimeAfter()) {
                String dateBefore = DateUtils.dateToString(dic.getUpdateTimeBefore());
                String dateAfter = DateUtils.dateToString(dic.getUpdateTimeAfter());
                wrapper.between("t.update_time", dateBefore, dateAfter);
            }
            if (StringUtils.isNotEmpty(dic.getName())) {
                wrapper.like("t.name", dic.getName(), SqlLike.DEFAULT);
            }
            if (StringUtils.isNotEmpty(dic.getLength())) {
                wrapper.like("t.length", dic.getLength(), SqlLike.DEFAULT);
            }
            if (StringUtils.isNotEmpty(dic.getLayer())) {
                wrapper.like("t.layer", dic.getLayer(), SqlLike.DEFAULT);
            }
            if (StringUtils.isNotEmpty(dic.getUpdateUserId())) {
                wrapper.like("t.update_user_id", dic.getUpdateUserId(), SqlLike.DEFAULT);
            }
            if (StringUtils.isNotEmpty(dic.getStatus())) {
                wrapper.like("t.status", dic.getStatus(), SqlLike.DEFAULT);
            }
            if (null != dic.getCreateTimeBefore() && null != dic.getCreateTimeAfter()) {
                String dateBefore = DateUtils.dateToString(dic.getCreateTimeBefore());
                String dateAfter = DateUtils.dateToString(dic.getCreateTimeAfter());
                wrapper.between("t.create_time", dateBefore, dateAfter);
            }
            if (StringUtils.isNotEmpty(page.getSort())) {
                wrapper.orderBy(CamelCaseUtil.toUnderlineName(page.getSort()), "asc".equals(page.getOrder()) ? true : false);
            }
        }
        List<DicVO> list = baseMapper.selectPageList(page, wrapper);
        page.setRecords(list);
        return page;
    }


    @Override
    public boolean deleteBatchIds(List<? extends Serializable> idList) {
        return super.deleteBatchIds(idList);
    }

    /**
     * 批量删除字典
     *
     * @param dics
     * @return
     */
    public boolean deleteBatch(List<DicVO> dics) throws CgException {
        boolean deleteState = false;
        List<String> ids = new ArrayList<String>();
        try {
            List<DicSet> dicSets = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(dics)) {
                for (int i = 0; i < dics.size(); i++) {
                    Dic dic = dics.get(i);
                    ids.add(dic.getId());
                    DicSet dicSet = new DicSet();
                    dicSet.setDicCode(dic.getCode());
                     dicSets.add(dicSet);
                }
                Dic dic = dics.get(0);
                DicVO dicVo = new DicVO();
                Father2Son.Copy(dic, dicVo);
                dicService.deleteBatchIds(ids);
                dicSetService.deleteBatch(dics, dicSets);
            }


        } catch (Exception e) {
            e.printStackTrace();
            throw new CgException(e.getMessage());
        }
        return deleteState;
    }


    /**
     * 保存的时候清除所有字典的缓存数据
     *
     * @param dic
     * @return
     */
    //@CacheEvict(value = "dic",allEntries=true)
    @Override
    public boolean insert(DicVO dic) throws CgException {
        try {
            PmUser sessionUser = ShiroUtil.getSessionUser();
            PmUserVO userCache = (PmUserVO) redisTemplate.opsForValue().get("userSession_" + sessionUser.getId());

            if (null != userCache) {
                dic.setUserId(userCache.getId());
            }
            dic.setCreateTime(new Date());
            dic.setId(IdWorker.get32UUID());

            EntityWrapper wrapper = new EntityWrapper<Dic>();
            wrapper.setSqlSelect("cast(max(code+'') as signed integer) id");

            Object o = dicService.selectObj(wrapper);
            if (null == o) {
                o = "0";
            }
            int max = Integer.parseInt(o.toString()) + 1;
            //TODO 前补零方法一
            DecimalFormat g1 = new DecimalFormat("000000");
            String code = g1.format(max);
            dic.setCode(code);
            baseMapper.insert(dic);

            dicService.insertDicSet(dic);
            return true;
        } catch (Exception e) {
            throw new CgException(e.getMessage());
        }
    }


    @Override
    public void update(DicVO dic) {
        if (null == dic || StringUtils.isBlank(dic.getId())) {
            throw new CgException("修改对象不能为空");

        }
        Dic dic1 = dicService.selectById(dic.getId());

        DicVO dic2 = new DicVO();
        Father2Son.Copy(dic1, dic2);
        dic2.setSets(dic.getSets());

        dicService.updateByKey(dic2);
        dicService.insertDicSet(dic2);


    }
	@Override
    public String validateDName(String name, String key) {
        EntityWrapper wrapper = new EntityWrapper<Dic>();
        wrapper.eq("name",name);
        String primaryKey = "";
        String validateInfo = super.validateNameRepeatByKey(key, primaryKey, wrapper);
        return validateInfo;

    }

    @Override
    public Dic validateDicName(String name) {
        return baseMapper.validateDicName(name);
    }


    @Override
    public void insertDicSet(DicVO dic) {
        List<DicSet> dicSets = dic.getSets();
        if (CollectionUtils.isNotEmpty(dicSets)) {
            //先删后插
            List<DicVO> dics = new ArrayList<DicVO>();
            dics.add(dic);
            dicSetService.deleteBatch(dics, dicSets);
            dicSetService.insertBatch(dic, dicSets);
        } else {
            throw new CgException("字典项不能为空");
        }
    }

    @Override
    public DicVO selectDicVOById(String id) {

        Dic dic = dicService.selectById(id);
        DicVO dicVO = new DicVO();
        Father2Son.Copy(dic, dicVO);
        EntityWrapper wrapper = new EntityWrapper<Dic>();
        wrapper.eq("dic_code", dicVO.getCode());
        List<DicSet> dicSets = dicSetService.selectList(wrapper);
        dicVO.setSets(dicSets);
        return dicVO;
    }

    /**
     * 通过主键更新字典的缓存数据
     *
     * @param dic
     * @return
     */
    //@CachePut(value = "dic", key = "#dic.id")
    public Dic updateByKey(Dic dic) throws CgException {
        try {
            PmUser sessionUser = ShiroUtil.getSessionUser();
            dic.setUpdateTime(new Date());
            dic.setUpdateUserId(sessionUser.getId());
            super.updateById(dic);
        } catch (RuntimeException e) {
            throw new CgException(e.getMessage());
        }
        return dic;
    }


    /**
     * 删除的时候同步字典的缓存数据
     *
     * @param id 主键
     * @return
     */
    //@CacheEvict(value = "dic", key = "#id")
    @Override
    public boolean deleteById(Serializable id) {

        return super.deleteById(id);
    }


    /**
     * 查询时保存字典的缓存数据
     *
     * @param id 主键
     * @return
     */
    //@Cacheable(value = "dic", key = "#id")
    @Override
    public Dic selectById(Serializable id) {
        return super.selectById(id);
    }

    @Override
    public String checkRepeat(Map map) {
        String name = map.get("name") + "";
        String value = map.get("value") + "";
        String key = map.get("key") + "";
        int count = baseMapper.queryCountByName(map);
//        如果key存在，则是修改，否则是新增
        if (StringUtils.isNotBlank(key)) {
            /*如果是更新，则数字可以大于1*/
            if (count <= 0) {
                return "true";
            } else if (count > 1) {//说明存在多个
                return "false";
            } else if (count == 1) {

                EntityWrapper wrapper = new EntityWrapper<Dic>();
                wrapper.eq(name, value);
                List<Dic> dics = baseMapper.selectList(wrapper);
                String checkExit = "true";
                if (CollectionUtils.isNotEmpty(dics)) {
                    for (int i = 0; i < dics.size(); i++) {
                        Dic dic = dics.get(i);
//                        说明当前值象存在于不同的对象之中，也不能重复
                        if (!StringUtils.equals(dic.getId().trim(), key.trim())) {
                            checkExit = "false";
                        }
                    }
                }
                return checkExit;
            } else {
                return "true";
            }
        } else {
            /*如果是新增，则数字可以大于0*/
            if (count > 0) {
                return "false";
            } else {
                return "true";
            }
        }
    }

    @Override
    public List<Dic> selectList(Dic dic) {
        EntityWrapper wrapper = new EntityWrapper<Dic>();
        if (StringUtils.isNotEmpty(dic.getUserId())) {
            wrapper.eq("user_id", dic.getUserId());
        }
        if (StringUtils.isNotEmpty(dic.getId())) {
            wrapper.eq("id", dic.getId());
        }
        if (StringUtils.isNotEmpty(dic.getOrgId())) {
            wrapper.eq("org_id", dic.getOrgId());
        }

        if (StringUtils.isNotEmpty(dic.getName())) {
            wrapper.eq("name", dic.getName());
        }
        if (StringUtils.isNotEmpty(dic.getLength())) {
            wrapper.eq("length", dic.getLength());
        }
        if (StringUtils.isNotEmpty(dic.getLayer())) {
            wrapper.eq("layer", dic.getLayer());
        }
        if (StringUtils.isNotEmpty(dic.getUpdateUserId())) {
            wrapper.eq("update_user_id", dic.getUpdateUserId());
        }
        if (StringUtils.isNotEmpty(dic.getStatus())) {
            wrapper.eq("status", dic.getStatus());
        }

        List<Dic> list = selectList(wrapper);
        return list;
    }
}